package com.drug.controller;

import com.drug.domain.*;
import com.drug.service.DeliveryService;
import com.drug.util.DateUtils;
import com.drug.util.ExcelUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/DeliveryController")
public class DeliveryController {

    @Autowired
    private DeliveryService deliveryService;
    /**
     * 查询所有的采购单信息
     * @return
     */
    @ResponseBody
    @RequestMapping("/findPurchaseOrder")
    private Result findPurchaseOrder(@RequestParam Map<String,Object> map){
          return deliveryService.findPurchaseOrder(map);
    }
    /**
     * 导出采购单信息
     *
     */
    @ResponseBody
    @RequestMapping(value = "/findAllPo")
    public String export(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String message = "";
        //获取数据
        List<PodiPd> list = deliveryService.findAllPo();
        //excel标题
        String[] title = {"采购单编号","采购单名称","采购医院","开始采购时间","结束采购时间","流水号","通用名","商品名","剂型","规格","单位","转换系数","生产企业","中标价","交易价","采购量","采购金额","供货企业"};
        //excel文件名
        String fileName = "PurchaseOrder"+System.currentTimeMillis()+".xls";
        //sheet名
        String sheetName = "采购单信息表";
        String [][] content = new String[list.size()][];
        for (int i = 0; i < list.size(); i++) {
            content[i] = new String[title.length];
            PodiPd podiPd = list.get(i);
            if (podiPd!=null){
                //采购单编号
                PurchaseOrder purchaseOrder = podiPd.getPurchaseOrder();
                if (purchaseOrder!=null){
                    String poNumber = purchaseOrder.getPoNumber();
                    content[i][0] = poNumber+"";
                    //采购单名称
                    String poName = purchaseOrder.getPoName();
                    content[i][1] = poName+"";
                    //开始采购时间
                    Date poSubmissionTime = purchaseOrder.getPoSubmissionTime();
                    String date2String = DateUtils.date2String(poSubmissionTime,"yyyy-MM-dd");
                    content[i][3] = date2String+"";
                    //结束采购时间
                    Date auditTime = purchaseOrder.getPoAuditTime();
                    String date2String1 = DateUtils.date2String(auditTime, "yyyy-MM-dd");
                    content[i][4] = date2String1+"";
                }
                //采购医院
                Hospital hospital = podiPd.getHospital();
                if (hospital!=null){
                    String hName = hospital.gethName();
                    content[i][2] = hName+"";
                }
                DrugInformation drugInformation = podiPd.getDrugInformation();
                if (drugInformation!=null){
                    //药品流水号
                    String diNumer = drugInformation.getDiNumer();
                    content[i][5] = diNumer+"";
                    //通用名
                    String diName = drugInformation.getDiName();
                    content[i][6] = diName+"";
                    //剂型
                    String diForm = drugInformation.getDiForm();
                    content[i][8] = diForm+"";
                    //规格
                    String diSpecifications = drugInformation.getDiSpecifications();
                    content[i][9] = diSpecifications+"";
                    //单位
                    String diUnit = drugInformation.getDiUnit();
                    content[i][10] = diUnit+"";
                    //转换系数
                    String diCc = drugInformation.getDiCc();
                    content[i][11] = diCc+"";
                    //中标价
                    BigDecimal diNewPrice = drugInformation.getDiNewPrice();
                    content[i][13] = diNewPrice+"";
                    content[i][14] = diNewPrice+"";
                }
                DrugAtegory drugAtegory = podiPd.getDrugAtegory();
                if (drugAtegory!=null){
                    String daName = drugAtegory.getDaName();
                    //商品名
                    content[i][7] = daName+"";
                    //供货企业
                    String daSupplier = drugAtegory.getDaSupplier();
                    content[i][17] = daSupplier+"";
                }
                //生产企业
                Manufacturer manufacturer = podiPd.getManufacturer();
                if (manufacturer!=null){
                    String mfName = manufacturer.getMfName();
                    content[i][12] = mfName+"";
                }
                //采购量
                Integer podiNumber = podiPd.getPodiNumber();
                content[i][15] = podiNumber+"";
                //采购总金额
                String podiTotal = podiPd.getPodiTotal();
                content[i][16] = podiTotal+"";
            }
        }
        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
            message = "SUCCESS";
        } catch (Exception e) {
            e.printStackTrace();
            message = "ERROR";
        }
        return null;
    }

    private void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(),"utf-8");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 下载模板
     * @param response
     * @param request
     * @throws IOException
     */
    @RequestMapping(value="/download",produces ="application/json;charset=UTF-8")
    public void downloadSampleInfo(HttpServletResponse response, HttpServletRequest request) throws IOException {
        OutputStream os = null;// 输出流
        File path = new File(ResourceUtils.getURL("classpath:static/download/aa.xls").getPath());
        InputStream fis = new FileInputStream(path);
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook(fis);
        String fileName = "发货导入模板.xls";
        new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
        os = response.getOutputStream();
        hssfWorkbook.write(os);
        os.flush();
        os.close();
    }

    /**
     * 表格导入
     * @param file
     * @param request
     * @param
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/inputExcel")
    public String poiInfo(@RequestParam("file") MultipartFile file,HttpServletRequest request,HttpServletResponse response) throws Exception {
        List<List<Object>> list = ExcelUtil.getExcelList(file.getInputStream(), file.getOriginalFilename());
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        for (int i = 0; i < list.size(); i++) {
            List<Object> li = list.get(i);
            String purchaseOrder = (String) li.get(0);
            String hospital = (String) li.get(1);
            String diNumer = (String) li.get(2);
            String diName = (String) li.get(3);
            String daName = (String) li.get(4);
            String diForm = (String) li.get(5);
            String diSpecifications = (String) li.get(6);
            String diUnit = (String) li.get(7);
            String diCc = (String) li.get(8);
            String manufacturer = (String) li.get(9);
            Goods goods = new Goods();
            goods.setPurchaseOrder(purchaseOrder);
            goods.setHospital(hospital);
            goods.setDiNumer(diNumer);
            goods.setDiName(diName);
            goods.setDaName(daName);
            goods.setDiForm(diForm);
            goods.setDiSpecifications(diSpecifications);
            goods.setDiUnit(diUnit);
            goods.setDiCc(diCc);
            goods.setManufacturer(manufacturer);
            deliveryService.InsertInfo(goods);
            response.getWriter().write( "<script>alert('导入成功')</script>");
        }
            return null;
    }

    /**
     * 选择发货
     *
     */
    @ResponseBody
    @RequestMapping("/reviseState")
    private Result  reviseState(Integer[] id){
        return deliveryService.reviseState(id);
    }
}
